<?php

namespace app\common\library;

use think\Db;
use think\Exception;

/**
 * 消息服务类 - 整合所有消息发送功能
 */
class MessageService
{
    protected $wechatMessage;
    protected $miniprogramMessage;

    public function __construct()
    {
        $this->wechatMessage = new WechatMessage();
        $this->miniprogramMessage = new MiniProgramMessage();
    }

    /**
     * 发送分工通知消息
     */
    public function sendAllocationMessage($userId, $allocationData)
    {
        try {
            $user = Db::name('user')->where('id', $userId)->find();
            if (!$user) {
                throw new Exception('用户不存在');
            }

            $result = [
                'internal' => false,
                'miniprogram' => false,
                'wechat' => false
            ];

            // 1. 发送站内消息
            if (config('wechat.message.enable_internal_push')) {
                $result['internal'] = $this->sendInternalMessage($userId, [
                    'type' => 'allocation',
                    'title' => '新的分工任务',
                    'content' => "您有新的分工任务：{$allocationData['order_no']} - {$allocationData['product_name']}",
                    'data' => $allocationData
                ]);
            }

            // 2. 发送小程序订阅消息
            if (config('wechat.message.enable_miniprogram_push') && !empty($user['openid'])) {
                try {
                    $result['miniprogram'] = $this->miniprogramMessage->sendAllocationNotification($user['openid'], $allocationData);
                } catch (Exception $e) {
                    \think\Log::error('发送小程序订阅消息失败：' . $e->getMessage());
                }
            }

            // 3. 发送微信公众号模板消息
            if (config('wechat.message.enable_wechat_push') && !empty($user['openid'])) {
                try {
                    $result['wechat'] = $this->wechatMessage->sendAllocationNotification($user['openid'], $allocationData);
                } catch (Exception $e) {
                    \think\Log::error('发送微信公众号模板消息失败：' . $e->getMessage());
                }
            }

            return $result;
        } catch (Exception $e) {
            \think\Log::error('发送分工通知消息失败：' . $e->getMessage());
            return false;
        }
    }

    /**
     * 发送审核结果消息
     */
    public function sendAuditMessage($userId, $auditData)
    {
        try {
            $user = Db::name('user')->where('id', $userId)->find();
            if (!$user) {
                throw new Exception('用户不存在');
            }

            $result = [
                'internal' => false,
                'miniprogram' => false,
                'wechat' => false
            ];

            // 1. 发送站内消息
            if (config('wechat.message.enable_internal_push')) {
                $statusText = $auditData['status'] == 1 ? '审核通过' : '审核不通过';
                $result['internal'] = $this->sendInternalMessage($userId, [
                    'type' => 'audit',
                    'title' => '报工审核结果',
                    'content' => "您的报工已审核完成，结果：{$statusText}",
                    'data' => $auditData
                ]);
            }

            // 2. 发送小程序订阅消息
            if (config('wechat.message.enable_miniprogram_push') && !empty($user['openid'])) {
                try {
                    $result['miniprogram'] = $this->miniprogramMessage->sendAuditNotification($user['openid'], $auditData);
                } catch (Exception $e) {
                    \think\Log::error('发送小程序订阅消息失败：' . $e->getMessage());
                }
            }

            // 3. 发送微信公众号模板消息
            if (config('wechat.message.enable_wechat_push') && !empty($user['openid'])) {
                try {
                    $result['wechat'] = $this->wechatMessage->sendAuditNotification($user['openid'], $auditData);
                } catch (Exception $e) {
                    \think\Log::error('发送微信公众号模板消息失败：' . $e->getMessage());
                }
            }

            return $result;
        } catch (Exception $e) {
            \think\Log::error('发送审核结果消息失败：' . $e->getMessage());
            return false;
        }
    }

    /**
     * 发送系统通知消息
     */
    public function sendSystemMessage($userId, $systemData)
    {
        try {
            $user = Db::name('user')->where('id', $userId)->find();
            if (!$user) {
                throw new Exception('用户不存在');
            }

            $result = [
                'internal' => false,
                'miniprogram' => false,
                'wechat' => false
            ];

            // 1. 发送站内消息
            if (config('wechat.message.enable_internal_push')) {
                $result['internal'] = $this->sendInternalMessage($userId, [
                    'type' => 'system',
                    'title' => $systemData['title'] ?? '系统通知',
                    'content' => $systemData['content'] ?? '',
                    'data' => $systemData
                ]);
            }

            // 2. 发送小程序订阅消息
            if (config('wechat.message.enable_miniprogram_push') && !empty($user['openid'])) {
                try {
                    $result['miniprogram'] = $this->miniprogramMessage->sendSystemNotification($user['openid'], $systemData);
                } catch (Exception $e) {
                    \think\Log::error('发送小程序订阅消息失败：' . $e->getMessage());
                }
            }

            // 3. 发送微信公众号模板消息
            if (config('wechat.message.enable_wechat_push') && !empty($user['openid'])) {
                try {
                    $result['wechat'] = $this->wechatMessage->sendSystemNotification($user['openid'], $systemData);
                } catch (Exception $e) {
                    \think\Log::error('发送微信公众号模板消息失败：' . $e->getMessage());
                }
            }

            return $result;
        } catch (Exception $e) {
            \think\Log::error('发送系统通知消息失败：' . $e->getMessage());
            return false;
        }
    }

    /**
     * 发送站内消息
     */
    protected function sendInternalMessage($userId, $messageData)
    {
        try {
            $data = [
                'user_id' => $userId,
                'type' => $messageData['type'],
                'title' => $messageData['title'],
                'content' => $messageData['content'],
                'data' => json_encode($messageData['data'] ?? []),
                'is_read' => 0,
                'createtime' => time()
            ];

            $messageId = Db::name('scanwork_message')->insertGetId($data);
            return $messageId > 0;
        } catch (Exception $e) {
            \think\Log::error('发送站内消息失败：' . $e->getMessage());
            return false;
        }
    }

    /**
     * 批量发送系统通知
     */
    public function sendSystemMessageToAll($systemData, $userIds = [])
    {
        try {
            $query = Db::name('user')->where('status', 'normal');
            
            if (!empty($userIds)) {
                $query->whereIn('id', $userIds);
            }

            $users = $query->select();
            $results = [];

            foreach ($users as $user) {
                $results[$user['id']] = $this->sendSystemMessage($user['id'], $systemData);
            }

            return $results;
        } catch (Exception $e) {
            \think\Log::error('批量发送系统通知失败：' . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取用户未读消息数量
     */
    public function getUnreadMessageCount($userId)
    {
        try {
            return Db::name('scanwork_message')
                ->where('user_id', $userId)
                ->where('is_read', 0)
                ->count();
        } catch (Exception $e) {
            \think\Log::error('获取未读消息数量失败：' . $e->getMessage());
            return 0;
        }
    }

    /**
     * 标记消息为已读
     */
    public function markMessageAsRead($messageId, $userId)
    {
        try {
            return Db::name('scanwork_message')
                ->where('id', $messageId)
                ->where('user_id', $userId)
                ->update(['is_read' => 1]);
        } catch (Exception $e) {
            \think\Log::error('标记消息已读失败：' . $e->getMessage());
            return false;
        }
    }

    /**
     * 删除消息
     */
    public function deleteMessage($messageId, $userId)
    {
        try {
            return Db::name('scanwork_message')
                ->where('id', $messageId)
                ->where('user_id', $userId)
                ->delete();
        } catch (Exception $e) {
            \think\Log::error('删除消息失败：' . $e->getMessage());
            return false;
        }
    }
}
